package com.wut.easyexcel.controller;

import cn.hutool.core.util.StrUtil;
import com.wut.core.common.vo.BaseResponse;
import com.wut.core.controller.BaseController;
import com.wut.easyexcel.excel.MemberExcel;
import com.wut.easyexcel.excel.handler.MemberValidateHandler;
import com.wut.easyexcel.service.EasyExcelService;
import com.wut.easyexcel.utils.ExcelUtil;
import com.wut.utils.json.LocalJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequiredArgsConstructor
@RequestMapping("/easyexcel")
@Api(tags = "EasyExcel模块")
public class EasyExcelController extends BaseController {

    private final EasyExcelService easyExcelService;

    @GetMapping("/member/export")
    @ApiOperation("导出会员列表Excel")
    public void exportMember() {
        List<MemberExcel> memberList = LocalJsonUtil.getListFromJson("json/members.json", MemberExcel.class);
        ExcelUtil.writeExcelWithoutFailedMessage(memberList, MemberExcel.class, "会员信息表", "会员信息", response);
    }

    @GetMapping("/member/export/template")
    @ApiOperation("导出会员列表Excel模板")
    public void exportMemberTemplate() {
        ExcelUtil.writeExcelWithoutFailedMessage(new ArrayList<>(), MemberExcel.class, "会员信息表", "会员信息", response);
    }

    @PostMapping("/member/export/error")
    @ApiOperation("导出会员列表Excel错误信息")
    public void exportMemberError(@RequestParam("file") MultipartFile file) throws IOException {
        List<MemberExcel> memberList = ExcelUtil.readExcel(file, MemberExcel.class, new MemberValidateHandler());
        List<MemberExcel> failedList = memberList.stream().filter(excel -> StrUtil.isNotBlank(excel.getFailedMessage())).collect(Collectors.toList());
        List<MemberExcel> successList = memberList.stream().filter(excel -> StrUtil.isBlank(excel.getFailedMessage())).collect(Collectors.toList());
        ExcelUtil.writeExcel(failedList, MemberExcel.class, "会员信息表", "会员信息", response);
    }

    @PostMapping("/member/import")
    @ApiOperation("导入会员列表Excel")
    public BaseResponse<List<MemberExcel>> importMember(@RequestParam("file") MultipartFile file) throws IOException {
        List<MemberExcel> memberList = ExcelUtil.readExcel(file, MemberExcel.class, new MemberValidateHandler());
        return BaseResponse.SUCCESS("导入成功", memberList);
    }

    @GetMapping("/order/export")
    @ApiOperation("导出订单列表Excel")
    public void exportOrder() {
    }
}
